/**
 * Title:       AFPolicy.java
 * Copyright:   Copyright (c) 1996-2004 The Agent Factory Working Group. All rights reserved.
 * Licence:     This file is free software; you can redistribute it and/or modify
 *              it under the terms of the GNU Lesser General Public License as published by
 *              the Free Software Foundation; either version 2.1, or (at your option)
 *              any later version.
 *
 *              This file is distributed in the hope that it will be useful,
 *              but WITHOUT ANY WARRANTY; without even the implied warranty of
 *              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *              GNU Lesser General Public License for more details.
 *
 *              You should have received a copy of the GNU Lesser General Public License
 *              along with Agent Factory; see the file COPYING.  If not, write to
 *              the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 *              Boston, MA 02111-1307, USA.
 */
package com.agentfactory.platform.service;

import java.util.ArrayList;
import java.util.Iterator;
import com.agentfactory.platform.core.Agent;

/**
 * this class models a set of rights for a given platform service.  Each service has a global
 * security policy (the default right), and then a set of agent specific rights which are implemented
 * through the AFRight class.
 *
 * @author  Rem Collier
 */
public class AFPolicy {
    private int globalPolicy;
    private ArrayList rights;
    
    /** Creates a new instance of ServicePolicy */
    public AFPolicy(int globalPolicy) {
        this.globalPolicy = globalPolicy;
        rights = new ArrayList();
    }
    
    public void addRight(Agent agent, int right) {
        rights.add(new AFRight(agent, right));
    }
    
    public void addRight(String name, int right) {
        rights.add(new AFRight(name, right));
    }

    public boolean hasAccess(String agent) {
        AFRight right = null;
        int index = -1;
        String testString = null;
        
        Iterator it = rights.iterator();
        while (it.hasNext()) {
            right = (AFRight) it.next();
            if (right.getAgentName().equals(agent)) {
                return right.isAllow();
            }
            index = right.getAgentName().indexOf('*');
            if (index > 0) {
                testString = right.getAgentName().substring(0, index);
                if (agent.startsWith(testString)) {
                    return right.isAllow();
                }
            }
        }
        
        return globalPolicy == AFRight.ALLOW;
    }
    
    public void setGlobalPolicy(int right) {
        globalPolicy = right;
    }
}
